<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow">
        <div>
          <a-form size="small" :model="pageData" layout="inline">
            <a-form-item label="类型名称" v-if="permissionStore.hasPermisson('cplx.cx')">
              <a-input :style="{ width: '200px' }" allow-clear class="bacClass" placeholder=""
                       v-model="pageData.dropDownData" @press-enter="huiche"/>
            </a-form-item>
          </a-form>
        </div>
        <div>
          <Toolbar :items="store.pageData.btnList" @add="addHandler" @del="deleteHandler" @select="selectHandler"
                   @export="exports" @import="importHandler" @excel="downloadHandler">
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18"/>
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18"/>
        </a-divider>
      </div>
    </template>

    <template #pageTabel>
      <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height: 100%; width: 100%; z-index: 999">
          <div style="width: 100%; height: 100%">
            <encapsulation-agrid ref="table1Ref" :configaggrid="configTable1"></encapsulation-agrid>
          </div>
      </a-spin>
    </template>
    <a-drawer style="z-index: 999" ok-text="保存" cancel-text="关闭" :drawer-style="{ zIndex: 9999 }"
              :mask-closable="false"
              :width="400" :visible="pageData.showAdd" :ok-loading="pageData.pageLoading" unmountOnClose @ok="sideOk"
              @cancel="pageData.showAdd = false">
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" layout="horizontal" :model="dataForm">
          <a-form-item label="名称" field="productTypeName" :rules="[{ required: true, message: '名称必填' }]"
                       :validate-trigger="['change', 'blur']">
            <a-input class="bacClass" placeholder="" v-model="dataForm.productTypeName"/>
          </a-form-item>
          <a-form-item label="备注" field="remark">
            <a-textarea class="bacClass" placeholder="" v-model="dataForm.remark" :max-length="400" allow-clear
                        show-word-limit/>
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>

<script lang="ts">
import {post} from '@/api/http'
import emitter from '@/hooks/useEventBus'
import {ref, reactive, onMounted, toRefs} from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import {Form, Message, Modal} from '@arco-design/web-vue'
import {FormInstance} from '@arco-design/web-vue/es/form'
import {String} from 'lodash'
import {baseURL} from '../../../api/axios.config'
import axios from 'axios'
import filedownload from 'js-file-download'
import usePermission from '@/store/modules/permission'
import {useProductInfoStore} from '@/store/product/productInfo'
import {storeToRefs} from 'pinia'

import {localeText} from '@/api/aggridZw'
import {pagingList} from '@/api/paging'
import {saveOrUpdateGridState as saveOrUpdateGridState01} from '@/hooks/useGridState'

interface ProdductTypeInfo {
  id: any
  code: string
  productTypeName: string
  // productTypeCode: string
  remark: string
}

export default {
  name: 'ProductInfo',
  setup() {
    const store = useProductInfoStore()
    const {total, page, size, pageData, selectedRowKeys, table, rowKey, tableColumns} =
        storeToRefs(store)
    const table1Ref = ref<any>(null)
    let tc: any[] = store.tableColumns.map((o: any) => {
      let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed'],
        tooltipField: o.key,
      }
      obj['width'] = 250
      if (o.slotName === 'action') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['lockPosition'] = 'right'
        obj['width'] = 90
        obj['cellRenderer'] = {
          template: `
            <a-tag class="tagCss" v-if="e" @click="a">修改</a-tag>`,
          setup(props: any) {
            const a = () => {
              editHandler(props.params.data)
            }
            return {
              e: store.pageData.isEdit,
              a,
            }
          },
        }
      }

      return obj
    })
    tc.unshift({
      showRowGroup: 'hide_def',
      headerName: "",
      "checkboxSelection": true,
      "headerCheckboxSelection": true,
      "pinned": "left",
      "width": 50,
      resizable: false,
      filter: false,
      sortable: false,
      minWidth: 50,
      maxWidth: 50,
      lockPosition: "left",
    })
    let configTable1 = {
      url: 'product/productType/getPage', //接口路径
      queryData: {
        //接口参数
        deleteState: 0,
        productTypeName: pageData.value.dropDownData
      },
      paginationShow: true, //分页是否显示
      invokeiIterface: true, //是否调用接
      rowMultiSelectWithClick: true, //点击行是否多选
      column: tc,
      fileName: 'ProductInfo-1'
    }

    function PageSize(val: any) {
      store.page = val
      doRefresh()
    }

    function change1(val: any) {
      store.size = val
      doRefresh()
    }

    const headerShow = ref<boolean>(true)

    async function doRefresh() {
      table1Ref.value.setQuery({
        deleteState: 0,
        productTypeName: pageData.value.dropDownData
      })
    }

    const tablediv = ref(null)
    //下拉框得到焦点
    const focusSel = () => {
      selCxAll({deleteState: 0})
    }
    //下拉数据
    const options = ref<any>(store.pageData.nameList)
    const loading = ref(false)
    const handleSearch = (value: any) => {
      if (value) {
        const ob = {
          key: value,
          deleteState: 0,
        }
        loading.value = true

        selCxAll(ob)
        options.value = store.pageData.nameList
        loading.value = false
      } else {
        options.value = []
      }
    }

    //下拉框查询
    function selCxAll(val: any) {
      post({
        url: 'product/productType/getProductTypeName',
        data: val,
      }).then(({data, code}: any) => {
        if (code === 200) {
          store.pageData.nameList = data
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }

    onMounted(() => {
      // 切换tap到本页面执行的方法
      // emitter.on('ProductInfo', () => {
      selCxAll({})
      doRefresh()
      // })
    })

    let cxbl = ''
    //查询
    const selectHandler = () => {
      store.page = 1
      cxbl = store.pageData.dropDownData
      doRefresh()
    }
    const queryData = reactive({
      clothType: '',
    })
    const addHandler = () => {
      //清空数据
      for (const key in dataForm) {
        if (key == 'id') {
          dataForm.id = null
        } else {
          dataForm[key] = ''
        }
      }
      store.pageData.showAdd = true
      store.pageData.sideTitle = '新增产品基础资料'
    }

    const dataForm = reactive<ProdductTypeInfo>({
      id: null,
      code: '',
      remark: '',
      // productTypeCode: '',
      productTypeName: '',
    })
    const gridOption = ref()
    const colState = ref()
    const gridReady = (params: any) => {
      gridOption.value = params.api
      colState.value = params.columnApi
    }

    const formRef = ref<FormInstance>()
    const sideOk = () => {
      formRef.value?.validate().then((err) => {
        if (!err) {
          //store.pageData.pageLoading = true;
          if (store.pageData.sideTitle === '新增产品基础资料') {
            post({
              url: 'product/productType/insert',
              data: [dataForm],
            })
                .then((res: any) => {
                  if (res.code === 200) {
                    formRef.value?.resetFields()
                    store.pageData.showAdd = false

                    Message.success({
                      content: '新增成功',
                      duration: 5000,
                    })
                  } else {
                    Message.error({
                      content: res.message,
                      duration: 5000,
                    })
                  }
                  doRefresh()
                })
                .finally(() => {
                  //store.pageData.pageLoading = false
                })
          } else {
            post({
              url: 'product/productType/update',
              data: [dataForm],
            })
                .then((res: any) => {
                  if (res.code === 200) {
                    formRef.value?.resetFields()
                    store.pageData.showAdd = false
                    //清空数据
                    for (const key in dataForm) {
                      if (key == 'id') {
                        dataForm.id = null
                      } else {
                        dataForm[key] = ''
                      }
                    }
                    Message.success({
                      content: '修改成功',
                      duration: 5000,
                    })
                    store.pageData.showAdd = false
                  } else {
                    Message.error({
                      content: res.message,
                      duration: 5000,
                    })
                  }
                  doRefresh()
                })
                .finally(() => {
                  store.pageData.pageLoading = false
                })
          }
        }
      })
    }
    const deleteHandler = () => {
      if (table1Ref.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return
      }
      Modal.confirm({
        title: '系统提示',
        content: '确认删除选中的数据?',
        onOk() {
          store.pageData.pageLoading = true
          post({
            url: 'product/productType/delete',
            data: table1Ref.value.getSelectedRows().map((o: any) => {
              return o.id
            }),
          })
              .then(({code, data}: any) => {
                if (code === 200) {
                  Message.success({
                    content: '删除成功',
                    duration: 5000,
                  })
                  store.page = 1
                  doRefresh()
                } else {
                  Message.error({
                    content: '修改失败',
                    duration: 5000,
                  })
                }
              })
              .finally(() => {
                store.pageData.pageLoading = false
              })
        },
      })
    }
    const editHandler = (record: ProdductTypeInfo) => {
      dataForm.id = record.id
      // dataForm.productTypeCode = record.productTypeCode
      dataForm.productTypeName = record.productTypeName
      dataForm.remark = record.remark
      store.pageData.sideTitle = '修改产品类型资料'
      store.pageData.showAdd = true
    }
    //判断是否填写了中文
    const isChiese = (value: string, cb: Function) => {
      return new Promise<void>((resolve) => {
        if (window.encodeURI(value).indexOf('%') !== -1) {
          cb('填写的值不能包含中文！')
        }
        resolve()
      })
    }
    //input离开焦点 将小写转大写
    // const inputBlur = () => {
    //   dataForm.productTypeCode = dataForm.productTypeCode.toUpperCase()
    // }
    //导出
    const exports = () => {
      if (table1Ref.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return
      } else {
        let idList: any = []
        table1Ref.value.getSelectedRows().forEach(function (o: any) {
          idList.push(o['id'])
        })
        //将表头拼接出来
        let head =
            '<th>序号</th><th>类型名称</th><th>备注</th><th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>'
        //拿到当前表格数据与勾选的行做筛选

        let nowRow = store.table.dataList.filter(function (o: any) {
          return (
              gridOption.value
                  .getSelectedRows()
                  .map((o: any) => {
                    return o.id
                  })
                  .indexOf(o['id']) !== -1
          )
        })
        let body = ''
        nowRow.forEach(function (o: any) {
          body += '<tr><td>' + o['productTypeCode'] + '</td>'
          body += '<td>' + o['productTypeName'] + '</td>'
          body += '<td>' + o['remark'] + '</td>'
          body += '<td>' + o['createName'] + '</td>'
          body += '<td>' + o['createTime'] + '</td>'
          body += '<td>' + o['updateName'] + '</td>'
          body += '<td>' + o['updateTime'] + '</td>'
          body += '</tr>'
        })
        tableToXlsx(head, '产品类型', body)
        console.log(table)
      }
    }

    function tableToXlsx(head: any, filename: any, body: any) {
      const uri = 'data:application/vnd.ms-excel;base64,',
          template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`

      const a = document.createElement('a')
      a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
      a.download = filename
      a.click()
      document.removeChild(a)
    }

    //模板下载
    const downloadHandler = () => {
      axios
          .get(baseURL + '/product/productType/uploadProductTypeModel', {
            responseType: 'blob',
            headers: {
              token: sessionStorage.getItem('USER-TOKEN-KEY'),
            },
          })
          .then((res) => {
            if (res.status === 200) {
              filedownload(res.data, '产品类型.xlsx')
            }
          })
    }
    //导入
    const importHandler = () => {
      const inputEle: HTMLInputElement = document.createElement('input')
      inputEle.type = 'file'
      inputEle.id = 'fileUploadExcel'
      inputEle.accept =
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
      inputEle.addEventListener('change', (e) => {
        const formData = new FormData()
        if (inputEle.files !== null) {
          formData.append('file', inputEle.files[0] || '')
        } else {
          Message.warning('未选择文件！')
          return
        }
        store.pageData.pageLoading = true
        axios
            .post(baseURL + '/product/productType/analyseProductTypeModelModel', formData, {
              headers: {
                'Content-Type': 'multipart/form-data',
                token: sessionStorage.getItem('USER-TOKEN-KEY'),
              },
            })
            .then((result) => {
              if (result.data['code'] === 200) {
                Message.success('导入成功')
              } else {
                Message.error(result.data.message)
              }
            })
            .finally(() => {
              store.pageData.pageLoading = false
              doRefresh()
            })
      })
      inputEle.click()
    }
    //设置权限
    // ['查询', '新增', '删除', '导出', '导入']
    const permissionStore = usePermission()

    if (permissionStore.hasPermisson('cplx.cx')) {
      store.pageData.btnList.push('查询')
    }
    if (permissionStore.hasPermisson('cplx.xz')) {
      store.pageData.btnList.push('新增')
    }
    if (permissionStore.hasPermisson('cplx.sc')) {
      store.pageData.btnList.push('删除')
    }
    if (permissionStore.hasPermisson('cplx.dc')) {
      store.pageData.btnList.push('导出')
    }
    if (permissionStore.hasPermisson('cplx.dr')) {
      store.pageData.btnList.push('导入')
    }
    if (permissionStore.hasPermisson('cplx.mbxz')) {
      store.pageData.btnList.push('模板下载')
    }
    if (permissionStore.hasPermisson('cplx.xg')) {
      store.pageData.isEdit = true
    }
    const handleChange = (_data: any) => {
      store.table.dataList = _data
    }
    const defaultColDef = {
      sortable: true,
      resizable: true,
      filter: true,
      //flex: 1
    }
    const huiche = () => {
      doRefresh()
    }
    const localeText1: any = ref(localeText)
    const pagingList1: any = ref(pagingList)
    return {
      colState,
      permissionStore,
      store,
      pagingList1,
      huiche,
      localeText1,
      defaultColDef,
      tc,
      total,
      PageSize,
      change1,
      page,
      size,
      handleChange,
      deleteHandler,
      sideOk,
      formRef,
      dataForm,
      addHandler,
      selectedRowKeys,
      tableColumns,
      table,
      rowKey,
      pageData,
      queryData,
      editHandler,
      selectHandler,
      // inputBlur,
      isChiese,
      exports,
      tablediv,
      options,
      loading,
      handleSearch,
      focusSel,
      downloadHandler,
      importHandler,
      headerShow,
      gridReady,
      table1Ref,
      configTable1
    }
  },
  components: {Toolbar, },
}
</script>
<style scoped lang="less"></style>